<template>
  <el-card shadow="never" class="aui-card--fill">
    <el-container style="display: flex; justify-content: start">
      <el-form
        size="mini"
        :inline="true"
        :model="queryForm"
        @keyup.enter.native="query()"
      >
        <el-form-item label="">
          <el-select v-model="queryForm.industry" placeholder="请选择行业名称">
            <el-option
              v-for="item in nameList"
              :key="item.label"
              :value="item.label"
              :label="item.label"
            ></el-option>
          </el-select>
          <!-- 行业 -->
          <!-- <ren-select v-model="queryForm.gender" dict-type="gender" :placeholder="$t('user.gender')"></ren-select> -->
        </el-form-item>
        <el-form-item label="">
          <el-input
            v-model="queryForm.indicatorName"
            placeholder="输入指标名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="query">查询</el-button>
          <el-button @click="clear">重置</el-button>
<!--          <el-button @click="deleteBtn" :disabled="selectedIds.length === 0"-->
<!--            >删除</el-button>-->
          <!-- <el-button type="success" @click="addOrUpdateHandle(null)"
            >新增指标</el-button
          > -->
        </el-form-item>
      </el-form>
    </el-container>
    <el-container style="height: 810px">
      <el-main>
        <div class="table-top">
          <div class="left">
            <div class="top-line"></div>
            预警处置列表
          </div>
          <div class="right">
<!--            <div class="table-top-btn" @click="addOrUpdateHandle()">新增</div>-->
            <div class="table-top-btn" @click="deleteBtn()">删除</div>
          </div>
        </div>
        <el-table
          :data="dataList"
          border
          stripe
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column
            prop="industry"
            label="行业"
            width="200"
          ></el-table-column>
          <el-table-column
            prop="indicatorName"
            label="指标名称"
            width="200"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="warningObjectName"
            label="预警对象"
            width="200"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="description"
            label="预警规则描述"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="reason"
            label="预警原因"
            width="200"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="warningTime"
            label="预警时间"
            width="200"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column fixed="right" label="操作" width="200">
            <template slot-scope="{ row }">
              <el-button
                @click="togglePushStatus(row)"
                type="text"
                size="small"
              >
                {{ row.pushStatus == "0" ? "取消推送" : "推送" }}
              </el-button>
              <el-button @click="clickHistory(row)" type="text" size="small"
                >历史</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          :current-page="page.pageNo"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="page.pageSize"
          :total="+page.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="pageSizeChangeHandle"
          @current-change="pageCurrentChangeHandle"
        >
        </el-pagination>
      </el-main>
    </el-container>
    <el-dialog title="历史" :visible.sync="historyShow" width="1200px">
      <div class="history-pop">
        <!-- <div style="position:relative">
            <img class="close-btn" src="../../../assets/img/close_icon.png" @click="closeBtn" alt="">
          </div> -->
        <div style="margin: 50px 20px 20px 20px">
          <el-table :data="historyList" border style="width: 100%">
            <el-table-column
              prop="industry"
              label="行业"
              width="200"
            ></el-table-column>
            <el-table-column
              prop="indicatorName"
              label="指标名称"
              width="200"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              prop="warningObjectName"
              label="预警对象"
              width="200"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              prop="reason"
              label="预警原因"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              prop="warningTime"
              label="预警时间"
              width="200"
              show-overflow-tooltip
            ></el-table-column>
          </el-table>
          <el-pagination
            :current-page="historyPage.pageNo"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="historyPage.pageSize"
            :total="+historyPage.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="historyPageSizeChangeHandle"
            @current-change="historyPageCurrentChangeHandle"
          >
          </el-pagination>
        </div>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import { getDictDataList } from '@/utils'
const URL_GET_ALL_MODULE = '/cgjybzIndustry/getModuleInfo'
const URL_DELETE = '/cgjybzIndustry/delRelation'

function createForm (arg) {
  return {
    dataSourceType: '',
    isDisplay: '',
    name: '',
    quotaName: '',
    updateFrequency: ''
  }
}

export default {
  components: {
    // AddOrUpdate
  },
  name: 'QuotaIndex',
  data () {
    return {
      page: {
        pageNo: 1,
        pageSize: 10,
        total: 0
      },
      historyPage: {
        pageNo: 1,
        pageSize: 10,
        total: 0
      },
      dataList: [
        {
          industryName: '11111',
          quotaName: '11111',
          quotaData: '11111',
          quotaDescribe: '11111',
          quotaWhy: '111111',
          quotaTime: '1111'
        }
      ],
      // addOrUpdateVisible: false,
      // dataListLoading: false,
      queryForm: {
        indicatorName: '',
        industry: ''
      },
      historyShow: false,
      moduleTree: [],
      selectedModule: [],
      historyList: [],
      treeProps: {
        children: 'children',
        label: 'name'
      },
      selectedIds: [] // 所有选择的user的id的数组
    }
  },
  computed: {
    subModuleTree () {
      return this.moduleTree.reduce((ret, cur) => {
        ret = ret.concat(cur.children)
        return ret
      }, [])
    },
    nameList () {
      return this.moduleTree.reduce((ret, cur) => {
        ret = ret.concat(
          cur.children.map((c) => ({ label: c.name, value: c.key }))
        )
        return ret
      }, [])
    }
  },
  mounted () {
    this.initData()
    this.query()
    this.fetchTreeData()
  },
  activated () {
    this.query()
  },
  methods: {
    handleClick (row) {
      console.log(row)
    },
    // 推送取消推送
    togglePushStatus (row) {
      const operationText = row.pushStatus === '0' ? '取消推送' : '开启推送'
      this.$confirm(`确定要${operationText}吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            // 调用接口删除
            const params = {
              id: row.id,
              pushStatus: row.pushStatus == '1' ? '0' : '1'
            }
            return this.$http
              .get('/cgjybzWarningInfo/pushMessage', { params })
              .then((res) => {
                this.$message.success(`${operationText}成功`)
                // 刷新表格数据
                this.query()
              })
              .catch((e) => {
                this.$message.error(`${operationText}，请稍后再试`)
                console.error(`${operationText}：`, e)
              })
              .finally(done)
          } else {
            done()
          }
        }
      })
    },
    // 历史
    clickHistory (row) {
      this.historyShow = true
      this.$http
        .post('/cgjybzWarningInfo/getWarningHistory', null, {
          params: {
            pageNum: this.historyPage.pageNo,
            pageSize: this.historyPage.pageSize,
            indicatorName: row.indicatorName
          }
        })
        .then(({ data: resp }) => {
          // this.dataListLoading = false
          this.historyPage.total = resp.total
          this.historyList = resp.list
        })
    },
    query () {
      this.$http
        .post('/cgjybzWarningInfo/getWarningList', null, {
          params: {
            ...this.queryForm,
            pageNum: this.page.pageNo,
            pageSize: this.page.pageSize
          }
        })
        .then(({ data: resp }) => {
          // this.dataListLoading = false
          this.page.total = resp.total
          this.dataList = resp.list
        })
    },
    //  这里的selection是你所有选择的项
    handleSelectionChange (selection) {
      this.selectedIds = selection.map((item) => item.id)
      console.log(selection)
    },
    fetchTreeData () {
      this.$http.get('/sys/warning/getAllIndex').then((res) => {
        this.moduleTree = res.data.data || []
      })
    },

    // 关闭弹窗
    // closeBtn () {
    //   this.historyShow = false
    // },
    deleteBtn () {
      if (this.selectedIds.length === 0) {
        return this.$message({
          message: this.$t('prompt.deleteBatch'),
          type: 'warning'
        })
      }
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http
          .post('/cgjybzWarningInfo/deleteWarningInfo', null, {
            params: {
              ids: this.selectedIds
            }
          })
          .then(({ data: resp }) => {
            this.$message.success('删除成功')
            this.query()
          })
      })
      // this.$http
      //   .post("/cgjybzWarningInfo/deleteWarningInfo", null, {
      //     params: {
      //       ids: this.selectedIds,
      //     },
      //   })
      //   .then(({ data: resp }) => {
      //     this.$message.success("删除成功");
      //     this.query();
      //   });
    },
    // deleteHandle (id) {
    //   this.$confirm(
    //     this.$t('prompt.info', { handle: this.$t('delete') }),
    //     this.$t('prompt.title'),
    //     {
    //       confirmButtonText: this.$t('confirm'),
    //       cancelButtonText: this.$t('cancel'),
    //       type: 'warning'
    //     }
    //   )
    //     .then(() => {
    //       this.$http
    //         .post(URL_DELETE, null, {
    //           params: {
    //             id
    //           }
    //         })
    //         .then(({ data: res }) => {
    //           if (res.code !== 0) {
    //             return this.$message.error(res.msg)
    //           }
    //           this.$message({
    //             message: this.$t('prompt.success'),
    //             type: 'success',
    //             duration: 500,
    //             onClose: () => {
    //               this.query()
    //             }
    //           })
    //         })
    //         .catch(() => {})
    //     })
    //     .catch(() => {})
    // },
    getDictDataList,
    addOrUpdateHandle (row) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(row)
      })
    },
    clear () {
      // this.queryForm = [];
      // this.page.pageNo = 1;
      Object.assign(this.$data, this.$options.data.bind(this)())
      this.initData()
      this.query()
      this.fetchTreeData()
    },
    // 分页, 每页条数
    pageSizeChangeHandle (val) {
      this.page.pageNo = 1
      this.page.pageSize = val
      this.query()
    },
    // 分页, 当前页
    pageCurrentChangeHandle (val) {
      this.page.pageNo = val
      this.query()
    },
    // 历史弹窗分页, 每页条数
    historyPageSizeChangeHandle (val) {
      this.historyPage.pageNo = 1
      this.historyPage.pageSize = val
      this.clickHistory()
    },
    // 历史弹窗分页, 当前页
    historyPageCurrentChangeHandle (val) {
      this.historyPage.pageNo = val
      this.clickHistory()
    },
    handleCurrentChange (data) {
      console.log('current-change ', data)
      if (data.isLeaf) {
        this.selectedModule = [data.id]
      }
      this.query()
    },
    handleCheckChange () {
      this.selectedModule = this.$refs.tree.getCheckedKeys(true)
      this.query()
    },
    initData () {
      this.$http.get(URL_GET_ALL_MODULE).then(({ data: resp }) => {
        const { data } = resp
        const tree = data.reduce((ret, cur) => {
          if (ret.findIndex((d) => d.name === cur.division) < 0) {
            const children = data
              .filter((d) => {
                return d.division === cur.division
              })
              .reduce((ret1, cur1) => {
                if (
                  ret1.findIndex(
                    (dd) => dd.industryName === cur1.industryName
                  ) < 0
                ) {
                  ret1.push({
                    name: cur1.industryName,
                    ...cur1
                  })
                }
                return ret1
              }, [])

            children.forEach((c) => {
              const grandson = data
                .filter((d) => {
                  return c.industryName === d.industryName
                })
                .reduce((rm, rcur) => {
                  if (
                    rm.findIndex((r) => r.industryType === rcur.industryType) <
                    0
                  ) {
                    rm.push({
                      name: rcur.industryType,
                      ...rcur,
                      isLeaf: true
                    })
                  }
                  return rm
                }, [])
              c.children = grandson
            })

            ret.push({
              name: cur.division,
              ...cur,
              children
            })
          }
          return ret
        }, [])
        this.moduleTree = tree.filter((item) => item.name)
      })
    }
  }
}
</script>

<style scoped lang="scss">
.aui-card--fill {
  position: relative;
}
.history-pop {
  // width: 1098px;
  // height: 600px;
  // background: rgba(255,255,255,1);
  // position: absolute;
  // top: 0;
  // left:200px;
  z-index: 999;
}
.close-btn {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 20px;
  cursor: pointer;
}
</style>
